<?php
// error_reporting(E_ALL & ~E_NOTICE);//禁止输出保错
error_reporting(0);
header("Access-Control-Allow-Origin: *");
// header('Access-Control-Allow-Methods','GET,HEAD,POST,PUT,DELETE'); //允许客户端的请求方式
// header('Content-Type:application/json');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept,Authorization");

if(strtoupper($_SERVER['REQUEST_METHOD'])== 'OPTIONS'){ 
exit; 
}
$action = $_GET['action'];//路由 action为url中的参数
$reg = "/^\\+?[1-9]\\d*\$/";
switch ($action) {
    case 'search':
        search();
        break;
    case 'getList':
        getList();
        break;
    case 'detail':
        detail();
        break;
    case 'add':
        add();
        break;
    case 'delete':
        delete();
        break;
    case 'edit':
        edit();
        break;
}
/**查询服务器中的数据
 * 1、连接数据库,参数分别为 服务器地址 / 用户名 / 密码 / 数据库名称
 * 2、返回一个包含参数列表的数组
 * 3、遍历$sqls这个数组，并把返回的值赋值给 $s
 * 4、执行一条mysql的查询语句
 * 5、关闭数据库
 * 6、返回执行后的数据
 */
function query_sql($sql,$type="")
{
    $mysqli = new mysqli("localhost", "table", "admin123", "table");    
    mysqli_set_charset($mysqli, "utf8");//设置编码  
    if(mysqli_connect_errno())
    {
        echo mysqli_connect_error();
        die;
    }  
    // $sqls = func_get_args();//数组 传入多个参数
    // foreach ($sqls as $s) {
    //     $query = $mysqli->query($s);      
    // }
    // $row = $rs-> fetch_array();
    $query = $mysqli->query($sql); 
    $effectrow=$mysqli->affected_rows;  
    $mysqli->close();
    if($type){      
        return $effectrow;
    }else{
        return $query;
    }
 
}
//过滤特殊字符
function replaceSpecialChar($strParam)
{
    $regex = "/\\/|\\~|\\!|\\@|\\#|\\\$|\\%|\\^|\\&|\\*|\\(|\\)|\\_|\\+|\\{|\\}|\\:|\\<|\\>|\\?|\\[|\\]|\\,|\\.|\\/|\\;|\\'|\\`|\\-|\\=|\\\\|\\|/";
    return preg_replace($regex, "", $strParam);
}
function message($str, $type = 1)
{
    //默认1 失败
    $message = json_encode(array("code" => $type, "message" => $str), JSON_UNESCAPED_UNICODE);
    return $message;
}
//搜索 keyword
function search()
{ global $reg;
    $str = "<,>/?~`!@#%^&*()+|\\='";
    //不允许使用的字符
    $keyword = $_GET['keyword'];
   
    $page = isset($_GET['page']) ? $_GET['page'] : 1;
    $pagesize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 20;
    if (!preg_match($reg, $page)) {
        echo message("page应为正整数");
        return;
    }
    if (!preg_match($reg, $pagesize)) {
        echo message("pagesize应为正整数");
        return;
    }
    // if (!$keyword) {
    //     echo message("搜索时缺少请求参数keyword");
    //     return;
    // }
    // if ($keyword&&similar_text($keyword, $str) > 0) {
    //     echo message("你输入有特殊字符");
    //     return;
    // } else {
    // }    
        //过滤特殊字符        
        if($keyword&&mb_strlen($keyword,"utf-8")>0){  //存在keyword  为搜索
            if (similar_text($keyword, $str) > 0) {
                    echo message("你输入有特殊字符");
                    return;
             } 
            $keyword = replaceSpecialChar($keyword);
            $sql = "SELECT id,name,channel,admin_name,take_time,status FROM  8dteams_work_order WHERE name LIKE '%{$keyword}%' ||content LIKE '%{$keyword}%' ||admin_name LIKE '%{$keyword}%'
            order by take_time desc limit " . ($page - 1) * $pagesize . ",{$pagesize}";
        }else{
            //正常查询
            $sql = "select id,name,channel,admin_name,take_time,status from 8dteams_work_order  order by take_time desc limit " . ($page - 1) * $pagesize . ",{$pagesize}";
        }
        $query = query_sql($sql);
        $query2 = query_sql("select count(id) as count  from 8dteams_work_order");
        $row2 = $query2->fetch_assoc();
        $alltotal=intval($row2['count']);//总条数       
      
        // $realtotal= $alltotal;
        // $realtotal= count($data);
        if ($query&&$query2) {
            while ($row = $query->fetch_assoc()) {
                // $row[take_time] = date("Y-m-d ", $row[take_time]);              
                $data[] = $row;
            }
            $realtotal = ($keyword&&mb_strlen($keyword,"utf-8")>0) ? count($data):$alltotal;
            //转换成字符串JSON
            $json = json_encode(array("code" => 0, "message" => "查询成功！", "total" => $realtotal, "data" => $data), JSON_UNESCAPED_UNICODE);
            echo $json;
            return;
        } else {
            echo message("查询失败");
            return;
        }
}
//得到列表page pagesize
function getList()
{
    global $reg;
    $page = isset($_GET['page']) ? $_GET['page'] : 1;
    $pagesize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 20;
    if (!preg_match($reg, $page)) {
        echo message("page应为正整数");
        return;
    }
    if (!preg_match($reg, $pagesize)) {
        echo message("pagesize应为正整数");
        return;
    }
    $sql = "select id,name,channel,admin_name,take_time,status from 8dteams_work_order  order by take_time desc limit " . ($page - 1) * $pagesize . ",{$pagesize}";
    $query = query_sql($sql);
    $query2 = query_sql("select count(id) as count  from 8dteams_work_order");
    $row2 = $query2->fetch_assoc();
    if ($pagesize >= intval($row2['count']) && $page > 1) {
        echo message("请求超出最大条数");
        return;
    } else {
        if ($query && $query2) {
            while ($row = $query->fetch_assoc()) {
                // $row[take_time] = date("Y-m-d ", $row[take_time]);
                $data[] = $row;
            }
            $json = json_encode(array(
                "code" => 0,
                "message" => "查询成功！",
                "total" => intval($row2['count']),                
                "data" => $data,
            ), JSON_UNESCAPED_UNICODE);
            echo $json;
            return;
        } else {
            echo message("查询失败");
            return;
        }
    }
}
//详情
function detail()
{
    global $reg;
    $id = $_GET['id'];
    if (!$id) {
        echo message("缺少请求参数id或者id错误");
        return;
    }
    if (!preg_match($reg, $id)) {
        echo message("id错误");
        return;
    } else {
        $sql = "select * from 8dteams_work_order  where id={$id}";
        $query = query_sql($sql);
        if ($query) {
            while ($row = $query->fetch_assoc()) {
                // $row[take_time] = date("Y-m-d ", $row[take_time]);
                // $row[finish_time] = date("Y-m-d ", $row[finish_time]);
                // $row[create_time] = date("Y-m-d ", $row[create_time]);
                $row[status] = intval($row[status]);
                $data[] = $row;
            }
            $json = json_encode(array("code" => 0, "message" => "查询成功！", "total" => count($data), "data" => $data), JSON_UNESCAPED_UNICODE);
            //转换成字符串JSON
            echo $json;
            return;
        } else {
            echo message("查询失败");
            return;
        }
    }
}
//删除方法
function delete()
{  
    //  传过来的是字符串1,2,3
    global $reg;
    $id = $_GET['id'];  
    if (!$id) {
        echo message("删除时缺少请求参数id或者id错误");
        return;
    }
    $result = explode(",", $id);
    $res=true;
    foreach($result as $val){
        if (!preg_match($reg, $val)) {          
            $res=false;
            break;    
        } 
    }
    if($res){
         // $sql = "delete from 8dteams_work_order where id={$id}";
    $sql = "delete from 8dteams_work_order where  id in ($id)";
    if (query_sql($sql,"delete")>=1) {            
        echo message("删除成功!", 0);
        return;
    } else {
        echo message("删除失败！无效id");
        return;
    }
    }else{
        echo message("id校验错误");
    }
    
}
//新增
function add()
{     
    $json = $_REQUEST['value'];
    $json = json_decode($json, true);
    //首先转数组
    class person
    {
        public $name = "";
        public $channel = "";
        public $admin_name = "";        
        public $take_time = "";
        public $status = "";
        public $content = "";
    }
    $array = get_object_vars(new person());
    //可存字段数组
    foreach ($array as $key => &$value) {
        //& 可以更原数组
        $value = $json[$key];
    }
    // $values = array_map('mysql_escape_string', array_values($array));
    $values = array_values($array);
    //值
    $keys = array_keys($array);    
    //键名
    $sql = "INSERT INTO 8dteams_work_order (".implode(',', $keys).") VALUES ('".implode('\',\'', $values)."')";     
    // print_r ("INSERT INTO 8dteams_work_order (".implode(',', $keys).") VALUES ('".implode('\',\'', $values)."')"); 
    // return;
    //关键
    if (query_sql($sql,"add")===1) {   
        echo message("新增成功！", 0);
        return;
    } else {
        echo message("执行失败，参数错误");
        return;
    }
}
//修改
function edit()
{
    $id = $_REQUEST['id'];
    $json = $_REQUEST['value'];    
    if (!$id) {
        echo message("缺少id!");
        return;
    }
    if (!$json) {
        echo message("缺少value!");
        return;
    }
    $json = json_decode($json, true);
    //转数组后可以使用数组的方法
    // $copyJson=$json;
    foreach ($json as $key => &$value) {
        //& 可以更原数组
        $value = $key . "='" . $value . "'";
        // print_r ($value);
    }
    $values = array_values($json);
    $values = implode(',', $values);
    $sql = "update 8dteams_work_order set {$values} where id = {$id};";
    // print_r ("update 8dteams_work_order set {$values} where id = {$id};");
    // return;

    if (query_sql($sql)) {   
        echo message("修改成功！", 0);
        echo $message;
        return;
    } else {
        echo message("修改失败！参数错误");
        return;
    }
}
exit;
